<!-- src/components/Chat.vue -->
<template>
    <div class="chat-container">
        <!-- 消息显示区域 -->
        <el-card class="box-card message-area" ref="messageArea">
            <div v-for="(msg, index) in messages" :key="index" :class="['message', msg.role]">
                <div class="role">{{ msg.role === 'user' ? '我' : '客服' }}</div>
                <div class="content">{{ msg.content }}</div>
            </div>
            <div v-if="isLoading" class="typing-indicator">
                <div class="dot-flashing"></div>
                <span>客服正在输入...</span>
            </div>
        </el-card>

        <!-- 输入区域 -->
        <div class="input-area">
            <el-input v-model="inputMessage" @keyup.enter.prevent="sendMessage" placeholder="请输入您的问题" type="textarea"
                :rows="4" maxlength="500" show-word-limit></el-input>
            <el-button type="primary" @click="sendMessage" :loading="isLoading" style="margin-top: 10px;">
                {{ isLoading ? '发送中...' : '发送' }}
            </el-button>
        </div>
    </div>
</template>

<script setup>
import { ref, nextTick } from 'vue';
import { baseURL } from '../utils/http.js'; // 引入基础URL
const messages = ref([]);
const inputMessage = ref('');
const isLoading = ref(false);
const messageArea = ref(null);

const sendMessage = async () => {
    if (!inputMessage.value.trim() || isLoading.value) return;

    // 添加用户消息
    messages.value.push({ role: 'user', content: inputMessage.value });
    const userMessage = inputMessage.value;
    inputMessage.value = '';
    isLoading.value = true;

    try {
        const response = await fetch(`${baseURL}/api/chat`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
            },
            body: JSON.stringify(userMessage),
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let assistantMessage = '';
        let buffer = '';  // 缓冲区用于存储未完全处理的数据

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;
            let decodedChunk = decoder.decode(value, { stream: true });

            // 将之前未处理完的部分与当前块合并
            buffer += decodedChunk;

            // 使用正则表达式移除"data:"前缀
            buffer = buffer.replace(/data:/g, '').replace(/\s+/g, ' ').trim();

            // 处理<think>标签
            while (buffer.includes('<think>') && buffer.includes('</think>')) {
                const thinkStart = buffer.indexOf('<think>');
                const thinkEnd = buffer.indexOf('</think>') + '</think>'.length;

                // 获取<think>标签外的内容
                const beforeThink = buffer.slice(0, thinkStart);
                const afterThink = buffer.slice(thinkEnd);

                assistantMessage += beforeThink;
                updateAssistantMessage(assistantMessage);

                // 更新buffer为剩余部分
                buffer = afterThink;
            }
        }

        // 如果还有剩余未处理的内容，添加到最后的消息中
        if (buffer) {
            assistantMessage += buffer;
            updateAssistantMessage(assistantMessage);
        }
    } catch (error) {
        console.error('请求失败:', error);
        messages.value.push({ role: 'assistant', content: '服务连接失败，请稍后再试' });
    } finally {
        isLoading.value = false;
    }
};

const updateAssistantMessage = (content) => {
    if (
        messages.value.length === 0 ||
        messages.value[messages.value.length - 1].role !== 'assistant'
    ) {
        messages.value.push({ role: 'assistant', content: content });
    } else {
        messages.value[messages.value.length - 1].content = content;
    }

    // 自动滚动到底部
    nextTick(() => {
        if (messageArea.value) {
            messageArea.value.scrollTop = messageArea.value.scrollHeight;
        }
    });
};
</script>

<style scoped>
.chat-container {
    padding: 20px;
    min-height: calc(100vh - 110px);
    background-color: #f5f5f5;
}

.message-area {
    height: 400px;
    overflow-y: auto;
    margin-bottom: 20px;
}

.message {
    margin: 10px 0;
    padding: 10px;
    border-radius: 8px;
}

.message.user {
    background-color: #e0f7fa;
    text-align: right;
}

.message.assistant {
    background-color: #f0f9eb;
    text-align: left;
}

.role {
    font-weight: bold;
    margin-bottom: 5px;
}

.content {
    white-space: pre-wrap;
}

.typing-indicator {
    text-align: center;
    margin-top: 10px;
}

.dot-flashing {
    width: 4px;
    height: 4px;
    background-color: #000;
    border-radius: 50%;
    display: inline-block;
    animation: dot-flashing 1s infinite alternate;
}

@keyframes dot-flashing {
    0% {
        opacity: 0.2;
    }

    100% {
        opacity: 1;
    }
}

.input-area {
    text-align: center;
}

.el-input {
    margin-bottom: 10px;
}
</style>